package com.ycsj.goldmedalnewconcept.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.activity.ConnectWifiActivity;
import com.jdy.haoduoai.activity.MainActivity;
import com.jdy.haoduoai.model.LeMachine;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.socket.SocketInputThread;
import com.jdy.haoduoai.socket.SocketThreadManager;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.model.MemberType;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.activity.BabyHomeWorkActivity;
import com.ycsj.goldmedalnewconcept.activity.ClassListActivity;
import com.ycsj.goldmedalnewconcept.activity.ClassQueryActivity;
import com.ycsj.goldmedalnewconcept.activity.LeaveApprovalActivity;
import com.ycsj.goldmedalnewconcept.activity.ParentsEvaluationActivity;
import com.ycsj.goldmedalnewconcept.activity.PrepareLessonsActivity;
import com.ycsj.goldmedalnewconcept.activity.ScoreQueryActivity;
import com.ycsj.goldmedalnewconcept.activity.StudentFileActivity;
import com.ycsj.goldmedalnewconcept.activity.TeacherFansiListActivity;
import com.ycsj.goldmedalnewconcept.activity.ZhiboListActivity;
import com.ycsj.goldmedalnewconcept.bean.ClassinfoResponse;
import com.ycsj.goldmedalnewconcept.bean.XxLoginInfo;
import com.ycsj.goldmedalnewconcept.bean.XxLoginInfoTeacher;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.GsonUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.UiHelper;

import java.io.IOException;
import java.util.StringTokenizer;

//import com.ycsj.goldmedalnewconcept.activity.ConnectWifiActivity;

//新管理模块
public class NewManageFragment extends Fragment implements OnClickListener {

    private String role;
    private LinearLayout ll_jiaoshi1;
    private LinearLayout ll_jiaoshi2;
    private LinearLayout ll_jiaoshi3;
    private LinearLayout ll_jiaoshi4;
    private LinearLayout ll_jiazhang;
    private LinearLayout ll_jiazhang2;
    private LinearLayout ll_xiaozhang2;
    private LinearLayout ll_xiaozhang;
    private TextView beike;
    private TextView buzhizuoye;
    private TextView danganguanli;
    private TextView kaoqinguanli;
    private TextView kechenjindu;
    private TextView qingjiashenpi;
    private TextView zhibo;
    private TextView jiazhang_zhibo;
    private TextView xiaozhang_zhibo;
    private TextView xiaozhang_pingjia;
    //	private TextView jiazhang_teachershow;
    private TextView jiazhang_chengjichaxun;
    private TextView jiazhang_robot;
    private TextView teacher_robot;
    private TextView jiaoshiguanli;
    private TextView jiaoshipingjia;
    private TextView jiaoxueguanli;
    private TextView jinrizuoye;
    private TextView keshichaxun;
    private TextView xuexiaoguanli;
    private TextView jiaoxuefansi;
    private TextView jiaoshifengcai;
    private TextView chengjiguanli;
    private Intent intent;
    private String account;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        role = SPUtil.getString(getActivity(), "role", "");// 获取账号角色类型

        View view = inflater.inflate(R.layout.fragment_new_manage, null);


        account = SPUtil.getString(getActivity(), "account", "");
        initView(view);

        initData();

        if ("1".equals(role)) {
            ll_jiaoshi1.setVisibility(ll_jiaoshi1.GONE);
            ll_jiaoshi2.setVisibility(ll_jiaoshi2.GONE);
            ll_jiaoshi3.setVisibility(ll_jiaoshi3.GONE);
            ll_jiaoshi4.setVisibility(ll_jiaoshi4.GONE);

            ll_jiazhang.setVisibility(ll_jiazhang.VISIBLE);
            ll_jiazhang2.setVisibility(ll_jiazhang2.VISIBLE);

        } else if ("3".equals(role)) {
            ll_jiaoshi1.setVisibility(ll_jiaoshi1.GONE);
            ll_jiaoshi2.setVisibility(ll_jiaoshi2.GONE);
            ll_jiaoshi3.setVisibility(ll_jiaoshi3.GONE);
            ll_jiaoshi4.setVisibility(ll_jiaoshi4.GONE);

            ll_xiaozhang.setVisibility(ll_xiaozhang.VISIBLE);
            ll_xiaozhang2.setVisibility(ll_xiaozhang2.VISIBLE);
        } else if ("2".equals(role)) {

        } else {
            ll_jiaoshi1.setVisibility(ll_jiaoshi1.GONE);
            ll_jiaoshi2.setVisibility(ll_jiaoshi2.GONE);
            ll_jiaoshi3.setVisibility(ll_jiaoshi3.GONE);
            ll_jiaoshi4.setVisibility(ll_jiaoshi3.GONE);
        }
        return view;
    }

    private void initView(View view) {
        ll_jiaoshi1 = (LinearLayout) view.findViewById(R.id.ll_jiaoshi1);
        ll_jiaoshi2 = (LinearLayout) view.findViewById(R.id.ll_jiaoshi2);
        ll_jiaoshi3 = (LinearLayout) view.findViewById(R.id.ll_jiaoshi3);
        ll_jiaoshi4 = (LinearLayout) view.findViewById(R.id.ll_jiaoshi4);
        ll_jiazhang = (LinearLayout) view.findViewById(R.id.ll_jiazhang);
        ll_jiazhang2 = (LinearLayout) view.findViewById(R.id.ll_jiazhang2);
        ll_xiaozhang2 = (LinearLayout) view.findViewById(R.id.ll_xiaozhang2);
        ll_xiaozhang = (LinearLayout) view.findViewById(R.id.ll_xiaozhang);

        beike = (TextView) view.findViewById(R.id.beike);
        buzhizuoye = (TextView) view.findViewById(R.id.buzhizuoye);
        danganguanli = (TextView) view.findViewById(R.id.danganguanli);
        jiaoshipingjia = (TextView) view.findViewById(R.id.jiaoshipingjia);
        kaoqinguanli = (TextView) view.findViewById(R.id.kaoqinguanli);
        kechenjindu = (TextView) view.findViewById(R.id.kechenjindu);
        qingjiashenpi = (TextView) view.findViewById(R.id.qingjiashenpi);
        zhibo = (TextView) view.findViewById(R.id.zhibo);
        jiazhang_zhibo = (TextView) view.findViewById(R.id.jiazhang_zhibo);
        xiaozhang_zhibo = (TextView) view.findViewById(R.id.xiaozhang_zhibo);
        xiaozhang_pingjia = (TextView) view.findViewById(R.id.xiaozhang_pingjia);
        jiaoshiguanli = (TextView) view.findViewById(R.id.jiaoshiguanli);
        jiaoxueguanli = (TextView) view.findViewById(R.id.jiaoxueguanli);
        jinrizuoye = (TextView) view.findViewById(R.id.jinrizuoye);
        keshichaxun = (TextView) view.findViewById(R.id.keshichaxun);
        xuexiaoguanli = (TextView) view.findViewById(R.id.xuexiaoguanli);
        jiaoxuefansi = (TextView) view.findViewById(R.id.jiaoxuefansi);
        jiaoshifengcai = (TextView) view.findViewById(R.id.jiaoshifengcai);
        chengjiguanli = (TextView) view.findViewById(R.id.chengjiguanli);
//		jiazhang_teachershow = (TextView) view.findViewById(R.id.jiazhang_teachershow);
        jiazhang_chengjichaxun = (TextView) view.findViewById(R.id.jiazhang_chengjichaxun);
        jiazhang_robot = (TextView) view.findViewById(R.id.jiazhang_robot);
        teacher_robot = (TextView) view.findViewById(R.id.teacher_robot);
    }

    private void initData() {
        beike.setOnClickListener(this);
        buzhizuoye.setOnClickListener(this);
        danganguanli.setOnClickListener(this);
        kaoqinguanli.setOnClickListener(this);
        kechenjindu.setOnClickListener(this);
        qingjiashenpi.setOnClickListener(this);
        jiaoshipingjia.setOnClickListener(this);
        zhibo.setOnClickListener(this);
        jiazhang_zhibo.setOnClickListener(this);
        xiaozhang_zhibo.setOnClickListener(this);
        jiaoshiguanli.setOnClickListener(this);
        jiaoxueguanli.setOnClickListener(this);
        jinrizuoye.setOnClickListener(this);
        keshichaxun.setOnClickListener(this);
        xuexiaoguanli.setOnClickListener(this);
        jiaoxuefansi.setOnClickListener(this);
        jiaoshifengcai.setOnClickListener(this);
        chengjiguanli.setOnClickListener(this);
//		jiazhang_teachershow.setOnClickListener(this);
        jiazhang_chengjichaxun.setOnClickListener(this);
        xiaozhang_pingjia.setOnClickListener(this);
        jiazhang_robot.setOnClickListener(this);
        teacher_robot.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.teacher_robot:    //教师端  小小班
                //判断是否存在班级
                isClass();
                break;

            case R.id.jiazhang_robot:    //家长端  小小班
                //请求服务器接口小小班第三方登录的接口,成功后跳转到ConnectWifiActivity,失败提示验证失败
                httpByThirdLogin(1,"");
                break;

            case R.id.xiaozhang_pingjia:    //家长评价 管理端
                intent = new Intent(getActivity(), TeacherFansiListActivity.class);
                intent.putExtra("teachershowtype", "2");
                startActivity(intent);
                break;
            case R.id.jiaoxuefansi:    //教学与反思 管理端
                intent = new Intent(getActivity(), TeacherFansiListActivity.class);
                startActivity(intent);
                break;
            case R.id.jiaoshifengcai:  //教师风采  校长
                intent = new Intent(getActivity(), TeacherFansiListActivity.class);
                intent.putExtra("teachershowtype", "1");
                startActivity(intent);
                break;
//		case R.id.jiazhang_teachershow:  // 家长端 教师风采
//			intent = new Intent(getActivity(),TeacherShowActivity.class);
//			startActivity(intent);
//			break;
            case R.id.beike:            //教师端 反思
                intent = new Intent(getActivity(), ClassListActivity.class);
                intent.putExtra("view_type", "6");
                startActivity(intent);
                break;
            case R.id.buzhizuoye:
                intent = new Intent(getActivity(), ClassListActivity.class);
                intent.putExtra("view_type", "1");
                startActivity(intent);
                break;
            case R.id.danganguanli:
                intent = new Intent(getActivity(), StudentFileActivity.class);
                startActivity(intent);
                break;
            case R.id.jiazhang_chengjichaxun:
                intent = new Intent(getActivity(), ScoreQueryActivity.class);//家长成绩查询
                startActivity(intent);
                break;
            case R.id.kaoqinguanli:
                intent = new Intent(getActivity(), ClassListActivity.class);
                intent.putExtra("view_type", "4");
                startActivity(intent);
                break;
            case R.id.kechenjindu:

                intent = new Intent(getActivity(), ClassListActivity.class);
                intent.putExtra("view_type", "3");

                startActivity(intent);
                break;
            case R.id.qingjiashenpi:
                intent = new Intent(getActivity(), LeaveApprovalActivity.class);
                startActivity(intent);
                break;

            case R.id.zhibo:
            case R.id.xiaozhang_zhibo:
            case R.id.jiazhang_zhibo:
                intent = new Intent(getActivity(), ZhiboListActivity.class);
                startActivity(intent);
                break;

            case R.id.jiaoshiguanli://教师管理

                intent = new Intent(getActivity(), TeacherFansiListActivity.class);
                intent.putExtra("teachershowtype", "3");
                startActivity(intent);
                break;

            case R.id.jiaoshipingjia:  //家长评价
                intent = new Intent(getActivity(), ParentsEvaluationActivity.class);
                intent.putExtra("TEACHER_MOBILE", SPUtil.getString(getActivity(), "account", ""));
                startActivity(intent);
                break;

            case R.id.jinrizuoye:   //宝贝作业
                intent = new Intent(getActivity(), BabyHomeWorkActivity.class);

                startActivity(intent);
                break;
            case R.id.keshichaxun:
                intent = new Intent(getActivity(), ClassQueryActivity.class);
                startActivity(intent);
                break;
            case R.id.xuexiaoguanli://教学目标
                intent = new Intent(getActivity(), PrepareLessonsActivity.class);
                intent.putExtra("title", "教学目标");
                startActivity(intent);
                break;
            case R.id.chengjiguanli:
                intent = new Intent(getActivity(), ClassListActivity.class);
                intent.putExtra("view_type", "8");

                startActivity(intent);
                break;
        }
    }

    //判断是否存在班级
    private void isClass() {

        OkHttpClient mOkHttpClient = new OkHttpClient();
        // mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        FormEncodingBuilder builder = new FormEncodingBuilder();
        builder.add("type", "3");
        builder.add("userID",  account);

        Request request = new Request.Builder()
                .url(Constant.SERVER_URL + "AppClassMsg").post(builder.build())
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Request arg0, IOException arg1) {
            }

            @Override
            public void onResponse(Response arg0) throws IOException {
                // 解析Json数据，保存登录状态及身份信息

                Gson gson = new Gson();

                final String json = arg0.body().string();
                ClassinfoResponse fromJson = gson.fromJson(json,
                        ClassinfoResponse.class);
                Log.e("test", json);
                int size = 0;
                if (fromJson != null) {
                    if ("-1".equals(fromJson.state)
                            || "0".equals(fromJson.state)) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                Toast.makeText(getActivity(), "请先创建班级", Toast.LENGTH_SHORT)
                                        .show();
                            }
                        });
                        return;
                    }else{
                        if (fromJson.size != "") {
                            size = Integer.parseInt(fromJson.size);

                            if(size!=0){

                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        //请求服务器接口小小班第三方登录的接口,成功后跳转到ConnectWifiActivity,失败提示验证失败
                                        httpByThirdLogin(0,json);
                                    }
                                });
                            }else{
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {

                                        Toast.makeText(getActivity(), "请先创建班级", Toast.LENGTH_SHORT)
                                                .show();
                                    }
                                });
                            }
                        }
                    }
                }
            }
        });
    }

//    /**
//     *
//     *
//     */
//    private void storeUserInfo() {
//        SharedPreferences prefs = getActivity().getSharedPreferences(Constant.USER_INFO,
//                Context.MODE_PRIVATE);
//        prefs.edit().putString(Constant.TEL, tel.getText().toString()).apply();
//        prefs.edit().putString(Constant.PWD, password.getText().toString()).apply();
//    }



    /**
     * 请求小小班的第三方登录接口,type用于区分老师和家长,0是老师,1是家长
     * <p>
     * role为1代表老师端,当role为1时需要传入role_code为9
     * role_code 老师端是9,其它不用传值
     *
     * @param type
     */
    private void httpByThirdLogin(final int type,String json) {

        final String classjson = json;
        UiHelper.showDialog(getActivity(), "验证中...");
        OkHttpClient mOkHttpClient = new OkHttpClient();
        FormEncodingBuilder builder = new FormEncodingBuilder();
        builder.add("platform", "android");
        builder.add("mobile", SPUtil.getString(getActivity(), "account", ""));
        if (type == 0) {
            //老师
            builder.add("role", "1");
            builder.add("role_code", "9");
        } else if (type == 1) {
            //家长
            builder.add("role", "0");
        }
        Request request = new Request.Builder()
                .url("http://sapi.jdy520.com/api/2.0/member/third_login")
                .post(builder.build()).build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        UiHelper.dismissDialog();
                        // 请求失败,主线程更新UI操作
                        Toast.makeText(getActivity(), "网络错误",
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Response response) throws IOException {
                // 获取服务器返回的json数据
                final String json = response.body().string();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                //老师端
                if(type == 0){
                    final XxLoginInfoTeacher info = GsonUtil.jsonToBean(json, XxLoginInfoTeacher.class);
                    com.jdy.haoduoaiteacher.model.LeUser lu  = null;
                    if(info!=null){
                        lu = info.data;
                    }

                    com.jdy.haoduoaiteacher.util.LeConfig.isLogin = true;

                    MyTeacherApp.getInstance().setUser(lu);
                    com.jdy.haoduoaiteacher.util.Tools.saveLeUser(lu);

                    if (lu != null) {
                        com.jdy.haoduoaiteacher.util.LeConfig.PHONE_NUM = lu.id;
                        com.jdy.haoduoaiteacher.util.LeConfig.nickname = lu.nickname;
                    }

                    com.jdy.haoduoaiteacher.socket.SocketThreadManager stm = com.jdy.haoduoaiteacher.socket.SocketThreadManager.getInstance();

                    boolean bFind = false;
                    if (lu != null && com.jdy.haoduoaiteacher.util.Tools.isNotEmpty(lu.member_types)) {
                        for (MemberType item : lu.member_types) {
                            if (item.type_id ==1) {
                                bFind = true;
                                doPageRouteTeacher(classjson);
                                break;
                            }
                        }

                        if (!bFind) {
                            doPageRouteTeacher(classjson);
                        }
                    } else {

                        doPageRouteTeacher(classjson);
                    }



                }else if(type == 1){

                    try {
                        //解析服务器返回的数据
                        final XxLoginInfo info = GsonUtil.jsonToBean(json, XxLoginInfo.class);
                        LeUser lu = null;
                        if(info!=null){
                            lu = info.data;

                        }
                        com.jdy.haoduoaiteacher.util.LeConfig.isLogin = true;
                        SocketInputThread.kickOffline = false;

                        LeMachine leBaby = null;
                        if (lu != null) {
                            leBaby = lu.machine;
                        }

                        if (leBaby != null && !leBaby.toString().equals("null")
                                && Tools.isNotEmpty(leBaby.id)) {
                            LeConfig.isDeviceBinded = true;
                            LeConfig.MAC_ID = leBaby.id;
                            LeConfig.babyname = leBaby.name;

//                        getBabyAvatar(leBaby.avatar);
                            LeXiaoXiaoBanApp.getInstance().setBaby(leBaby);

                            String url = leBaby.ip;
                            if (Tools.isNotNullStr(url)) {
                                StringTokenizer tokens = new StringTokenizer(url, ":");
                                LeConfig.g_ServerIP = tokens.nextToken();
                                Log.e("LoginActivity", "============" + LeConfig.g_ServerIP);
                                LeConfig.FILE_PORT = Integer.parseInt(tokens.nextToken());
                                Log.e("LoginActivity", "============" + LeConfig.FILE_PORT);

                                SocketThreadManager.releaseInstance();
                                SocketThreadManager.getInstance().disconnectOldConnectNew();

                            }

                            if (lu != null && Tools.isNotEmpty(leBaby.name)
                                    && Tools.isNotEmpty(lu.nickname)) {
                                LeConfig.isInfoFilled = true;

                                if (Tools.isNotEmpty(leBaby.activate)
                                        && !leBaby.activate.toString().equals("null")) {
                                    LeConfig.isDeviceActivated = !leBaby.activate.is_expired;
                                    LeConfig.expiredAt = leBaby.activate.expired_at;
                                }
                            } else {
                                LeConfig.isInfoFilled = false;
                            }

                        } else {
                            LeConfig.isDeviceBinded = false;
                        }

                        if (lu != null) {
                            LeConfig.PHONE_NUM = lu.id;
                            LeConfig.nickname = lu.nickname;
                        }

                        LeXiaoXiaoBanApp.getInstance().setUser(lu);
                        Tools.saveLeUser(lu);
                        Tools.saveLeBaby(leBaby);

                        doPageRoute();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                    }
                });
            }
        });
    }

    private void doPageRoute() {

            if (LeConfig.isDeviceBinded) {

                    Intent intent = new Intent(getActivity(), MainActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);

            } else {
                Intent t = new Intent(getActivity(), ConnectWifiActivity.class);
                startActivity(t);

            }
            //关闭Dialog
            UiHelper.dismissDialog();
    }
    private void doPageRouteTeacher(String classjson) {

                SPUtil.putString(getActivity(), "classjson",
                classjson);


                Intent intent = new Intent(getActivity(), com.jdy.haoduoaiteacher.activity.MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
//        String clazz = SPUtil.getString(getActivity(), "classjson", "");
//        Log.i("classjson","班级的json"+clazz);

            //关闭Dialog
            UiHelper.dismissDialog();
    }
}



















